package com.itic.mobile.upload;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.aliyun.oss.OSSClient;
import com.itic.appbase.framework.utils.FileVo;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.configuration.PropertyHelper;
import com.itic.mobile.base.BaseMobile;

@Controller
@RequestMapping(value = "/mobile/upload")
public class UploadAliOssMobile extends BaseMobile {

	
	//private String endpoint = "http://oss-cn-qingdao.aliyuncs.com";
	private String endpoint = "http://oss-cn-beijing.aliyuncs.com";
	//private String accessKeyId = "LTAIvvdbn9S3XBxS";
	private String accessKeyId = "LTAIQysZPITfbNiz";
	
	//private String accessKeySecret = "YVVcyKI1D939KFj4VbqgaJ88f8gw8x";
	private String accessKeySecret = "FpGdlyobwWafMNLtDLl5iA45Xg8RUI";
	private String ob = "huifavideo";
	private String tempPath = PropertyHelper.getString("app.upload.path");
	/**
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/test")
	@ResponseBody
	public String test(HttpServletRequest request) {
		String url = "http://encihui.oss-cn-qingdao.aliyuncs.com/";
		try {

			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				multiRequest.setCharacterEncoding(request.getCharacterEncoding());// 获取编码格式
				Iterator<String> iterator = multiRequest.getFileNames();// 实现多文件上传，需要使<input
																		// type="file"
																		// name="file1">中的name值不同，如name="file1"，name="file2"
				while (iterator.hasNext()) {
					MultipartFile file = multiRequest.getFile(iterator.next());
					InputStream is = file.getInputStream();

					String endpoint = "http://oss-cn-qingdao.aliyuncs.com";
					// 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录
					// https://ram.console.aliyun.com 创建
					String accessKeyId = "LTAIvvdbn9S3XBxS";
					String accessKeySecret = "YVVcyKI1D939KFj4VbqgaJ88f8gw8x";
					// 创建OSSClient实例
					OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

					// 使用访问OSS
					// 上传文件流
					String fileName = "logo.png";

					ossClient.putObject("encihui", fileName, is);
					// 关闭client
					ossClient.shutdown();
					is.close();
					
					url += fileName;
				}
			}


		} catch (Exception e) {
			e.printStackTrace();
		}
		return url;
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/alioss")
	@ResponseBody
	public Map<String,Object> alioss(HttpServletRequest request,HttpServletResponse response ,String type ) {
	    String url = "http://huifavideo.oss-cn-beijing.aliyuncs.com/";
		Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
		try {

			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				multiRequest.setCharacterEncoding(request.getCharacterEncoding());// 获取编码格式
				Iterator<String> iterator = multiRequest.getFileNames();// 实现多文件上传，需要使<input
																		// type="file"
																		// name="file1">中的name值不同，如name="file1"，name="file2"
				while (iterator.hasNext()) {
					FileVo fileVo = new FileVo();
					MultipartFile file = multiRequest.getFile(iterator.next());
					InputStream is = file.getInputStream();
					String newName = "";
					if( StringHelper.isNotBlank(type) ){
						newName = type+"/";
					}
					String filename = file.getOriginalFilename();
					int lastIndexOf = filename.lastIndexOf(".");
                	if( lastIndexOf>0 ){
                		 String suffix = filename.substring(lastIndexOf);
                         newName += UUID.randomUUID().toString().concat(suffix);
                        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录
     					// https://ram.console.aliyun.com 创建
     					
     					// 创建OSSClient实例
     					OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

     					// 使用访问OSS
     					// 上传文件流
     					//String fileName = "image/logo.png";
     					
     					ossClient.putObject(ob, newName, is);
     					// 关闭client
     					ossClient.shutdown();
     					is.close();
     					
     					url += newName;
     					
     					fileVo.setUrl(url);
     					fileVo.setSize(file.getSize());
     					fileVo.setOrginName(filename);
     					
     					resultMap.put(DATA, fileVo);
     					errorCode = SUCCESS_ERROR_CODE;
     			       	errorMsg = SUCCESS_ERROR_MSG;
                    }else{
                    	errorCode = FILE_SUFFIX_ERROR_CODE;
    			       	errorMsg = FILE_SUFFIX_ERROR_MSG;
                    }
				}
			}else{
				errorCode = NOT_FILE_ERROR_CODE;
		       	errorMsg = NOT_FILE_ERROR_MSG;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		resultMap.put(CODE, errorCode);
	   	resultMap.put(MSG, errorMsg);
	   	isCrrossDomain(response);
	   	return resultMap;
	}

	
	/**
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/tencent")
	@ResponseBody
	public Map<String,Object> tencent(HttpServletRequest request,HttpServletResponse response ,String type ) {
	    String url = "https://uhuijia-1254600872.cos.ap-beijing.myqcloud.com/";
		Map<String, Object> resultMap = new HashMap<String,Object>();
	   	String errorCode = PARAM_ERROR_CODE;
	   	String errorMsg = PARAM_ERROR_MSG;
		try {

			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) { // 判断request是否有文件上传
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				multiRequest.setCharacterEncoding(request.getCharacterEncoding());// 获取编码格式
				Iterator<String> iterator = multiRequest.getFileNames();// 实现多文件上传，需要使<input
																		// type="file"
																		// name="file1">中的name值不同，如name="file1"，name="file2"
				while (iterator.hasNext()) {
					FileVo fileVo = new FileVo();
					MultipartFile file = multiRequest.getFile(iterator.next());
					String newName = "";
					if( StringHelper.isNotBlank(type) ){
						newName = type+"/";
					}
					String filename = file.getOriginalFilename();
					int lastIndexOf = filename.lastIndexOf(".");
                	if( lastIndexOf>0 ){
                		 String suffix = filename.substring(lastIndexOf);
                         newName += UUID.randomUUID().toString().concat(suffix);
                        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录
     					// https://ram.console.aliyun.com 创建
                        file.transferTo(new File(tempPath+newName));
                         //上传到云OSS里面
                        TencentOSSClient.uploadFile(newName,new File(tempPath+newName));
     					url += newName;
     					
     					fileVo.setUrl(url);
     					fileVo.setSize(file.getSize());
     					fileVo.setOrginName(filename);
     					
     					resultMap.put(DATA, fileVo);
     					errorCode = SUCCESS_ERROR_CODE;
     			       	errorMsg = SUCCESS_ERROR_MSG;
                    }else{
                    	errorCode = FILE_SUFFIX_ERROR_CODE;
    			       	errorMsg = FILE_SUFFIX_ERROR_MSG;
                    }
				}
			}else{
				errorCode = NOT_FILE_ERROR_CODE;
		       	errorMsg = NOT_FILE_ERROR_MSG;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		resultMap.put(CODE, errorCode);
	   	resultMap.put(MSG, errorMsg);
	   	isCrrossDomain(response);
	   	return resultMap;
	}
}